import {ProductModel} from "../../../database/models/Product";
import {ProductGroupModel} from "../../../database/models/ProductGroup";

export const typeDefs = `
 type ProductGroup{
   _id:String!
   name: String!
   description: String!
   priceInGem: Int!
   highestPrice: Float!
   category:String!
   state:String!
   sortNum: Int!
   hotNum: Int!

   level1: [Product]!
   level2: [Product]!
   level3: [Product]!
   level4: [Product]!
 }

  input ProductGroupInput{
   name: String!
   description: String!
   priceInGem: Int!
   category:String!
   state:String!
   sortNum: Int!
   hotNum: Int!

   level1: [String]!
   level2: [String]!
   level3: [String]!
   level4: [String]!
 }
`

export const queryDefs = `
  productGroups(page:Int,size:Int): [ProductGroup]!
  searchProductGroups(query:String!): [Product]!
`

export const mutationDefs = `
 createProductGroup(productGroup: ProductGroupInput!): ProductGroup
 updateProductGroup(_id: String!, productGroup: ProductGroupInput!): ProductGroup
 onStockProductGroup(_id: String!): Boolean
 offStockProductGroup(_id: String!): Boolean
 deleteGroup(_id: String!): Boolean
`

function resolveLevel(name: string) {

  return async (parent, args, context, info) => {
    const products = []

    for (const id of parent[name]) {
      products.push(await ProductModel.findById(id))
    }

    return products
  }
}

export const resolvers = {
  Query: {
    productGroups: async (_, {page = 0, size = 20}) => {
      return ProductGroupModel.find().skip(page * size).limit(size).sort({sortNum: -1}).lean()
    },
    searchProductGroups: async (_, {query}) => {
      const reg = new RegExp(query, 'gi')
      return ProductGroupModel.find({
        name: reg
      }).lean()
    }
  },

  Mutation: {
    createProductGroup: async (_, {productGroup}) => {
      const pg = await ProductGroupModel.create(productGroup)
      return pg
    },
    async updateProductGroup(_, {_id, productGroup}) {
      const pg = await ProductGroupModel.findByIdAndUpdate(_id, productGroup, {new: true})
      return pg
    },
    onStockProductGroup: async (_, {_id}) => {
      const pg = await ProductGroupModel.findByIdAndUpdate(_id, {state: `on`}, {new: true})
      return !!pg
    },
    offStockProductGroup: async (_, {_id}) => {
      const pg = await ProductGroupModel.findByIdAndUpdate(_id, {state: `off`}, {new: true})
      return !!pg
    },
    deleteGroup: async (_, {_id}) => {
      return ProductGroupModel.deleteOne({_id})
    }
  },

  ProductGroup: {
    level1: resolveLevel('level1'),
    level2: resolveLevel('level2'),
    level3: resolveLevel('level3'),
    level4: resolveLevel('level4')
  }
}
